package cn.com.smart.module.xman.etlMail.controller;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import cn.com.smart.common.utils.poi.ExcelUtil;
import cn.com.smart.framework.aspectj.lang.annotation.Log;
import cn.com.smart.framework.aspectj.lang.enums.BusinessType;
import cn.com.smart.framework.web.controller.BaseController;
import cn.com.smart.framework.web.domain.AjaxResult;
import cn.com.smart.framework.web.page.TableDataInfo;
import cn.com.smart.module.system.user.domain.User;
import cn.com.smart.module.system.user.service.IUserService;
import cn.com.smart.module.xman.etlMail.domain.Contact;
import cn.com.smart.module.xman.etlMail.domain.EtlMail;
import cn.com.smart.module.xman.etlMail.service.IContactService;
import cn.com.smart.module.xman.etlMail.service.IEtlMailService;

/**
 * 邮件列信息操作处理
 * 
 * @author xman
 * @date 2019-06-10
 */
@Controller
@RequestMapping("/xman/etlMail")
public class EtlMailController extends BaseController
{
	
	@Value("${smart.profile}")
    private String uploadPath;
	
    private String prefix = "xman/etlMail";
    
	@Autowired
	private IEtlMailService etlMailService;
	
	@Autowired
	private IContactService contactService;
	
	@Autowired
	private IUserService userService;
	
	@RequiresPermissions("xman:etlMail:view")
	@GetMapping()
	public String etlMail()
	{
	    return prefix + "/etlMail";
	}
	
	/**
	 * 查询邮件列列表
	 */
	@RequiresPermissions("xman:etlMail:list")
	@PostMapping("/list")
	@ResponseBody
	public TableDataInfo list(EtlMail etlMail)
	{
		startPage();
        List<EtlMail> list = etlMailService.selectList(etlMail);
		return getDataTable(list);
	}
	
	
	/**
	 * 导出邮件列列表
	 */
	@RequiresPermissions("xman:etlMail:export")
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(EtlMail etlMail)
    {
    	List<EtlMail> list = etlMailService.selectList(etlMail);
        ExcelUtil<EtlMail> util = new ExcelUtil<EtlMail>(EtlMail.class);
        return util.exportExcel(list, "etlMail");
    }
	
	@GetMapping("/detail")
	public String detail()
	{
	    return prefix + "/detail";
	}
	
	@PostMapping("/detail")
	@ResponseBody
	public AjaxResult detail(String id)
	{
		return AjaxResult.success(etlMailService.selectById(id));
	}
	
	/**
	 * 新增邮件列
	 */
	@GetMapping("/add")
	public String add()
	{
	    return prefix + "/add";
	}
	
	/**
	 * 新增保存邮件列
	 */
	@RequiresPermissions("xman:etlMail:add")
	@Log(title = "邮件列", businessType = BusinessType.INSERT)
	@PostMapping("/add")
	@ResponseBody
	public AjaxResult addSave(EtlMail etlMail, @RequestParam("files") List<MultipartFile> files)
	{
//		System.out.println(etlMail);
//		System.out.println(files.size());
//		if(StringUtils.isNotEmpty(etlMail.getId())) {
			if(etlMailService.insert(etlMail, files) == 1) {
				return AjaxResult.success("提交成");
			}
//		}
		return AjaxResult.error("提交失败");
	}

	/**
	 * 修改邮件列
	 */
	@GetMapping("/edit/{id}")
	public String edit(@PathVariable("id") String id, ModelMap mmap)
	{
		EtlMail etlMail = etlMailService.selectById(id);
		mmap.put("etlMail", etlMail);
	    return prefix + "/edit";
	}
	
	/**
	 * 修改保存邮件列
	 */
	@RequiresPermissions("xman:etlMail:edit")
	@Log(title = "邮件列", businessType = BusinessType.UPDATE)
	@PostMapping("/edit")
	@ResponseBody
	public AjaxResult editSave(EtlMail etlMail)
	{		
		return toAjax(etlMailService.updateById(etlMail));
	}
	
	/**
	 * 删除邮件列
	 */
	@RequiresPermissions("xman:etlMail:remove")
	@Log(title = "邮件列", businessType = BusinessType.DELETE)
	@PostMapping( "/remove")
	@ResponseBody
	public AjaxResult remove(String[] id)
	{	
		if(id != null && id.length > 0) {
			String ids = Arrays.toString(id).replace(" ", "");
			return AjaxResult.success(etlMailService.deleteBatchIds(ids.substring(1, ids.length() - 1)));
		}
		return AjaxResult.error("参数无效");
	}
	
	@GetMapping( "/contactList")
	@ResponseBody
	public AjaxResult contactList()
	{		
		List<User> contacts = userService.selectSimpleUserList();
		User user = (User) SecurityUtils.getSubject().getPrincipal();
		Contact contact = new Contact();
		contact.setUserId(user.getUserId());
		List<Contact> contactList = contactService.selectContactList(contact);
		Set<String> emails = new HashSet<String>();
		JSONArray array = new JSONArray(contacts.size() + contactList.size());
		contacts.forEach(u -> {
			if(StringUtils.isNotEmpty(u.getEmail())) {
				JSONObject json = new JSONObject(2);
				json.put("displayName", u.getUserName());
				json.put("email", u.getEmail());
				array.add(json);
				emails.add(u.getEmail());
			}
		});
		contactList.forEach(c -> {
			if(!emails.contains(c.getEmail())) {
				JSONObject json = new JSONObject(2);
				json.put("displayName", c.getName());
				json.put("email", c.getEmail());
				array.add(json);
			}
		});
		return AjaxResult.success(array);
	}
	
	@GetMapping( "/userList")
	@ResponseBody
	public AjaxResult userList()
	{		
		List<User> users = userService.selectSimpleUserList();
		JSONArray array = new JSONArray(users.size());
		users.forEach(u -> {
			if(StringUtils.isNotEmpty(u.getEmail())) {
				JSONObject json = new JSONObject(2);
				json.put("id", u.getUserId());
				json.put("displayName", u.getUserName());
				array.add(json);
			}
		});
		return AjaxResult.success(array);
	}
	
	@GetMapping("/fileDownload")
	@ResponseBody
    public AjaxResult fileDownload(String fileName, String originalName, HttpServletResponse response) {
		if(StringUtils.isNotEmpty(fileName)) {
			File file = new File(uploadPath + "upload/" + fileName);
			if(file.exists()) {
				BufferedInputStream bis = null;
				final int MAX_SIZE = 4096;
				int len;
				byte[] buffer = new byte[MAX_SIZE]; 
				try {
	    			response.setHeader("content-disposition", "attachment;filename=" + URLEncoder.encode(StringUtils.isEmpty(originalName)?fileName:originalName, "UTF-8"));
	    			response.addHeader("Content-Length","" + file.length());
	    			bis = new BufferedInputStream(new FileInputStream(file));
	    			OutputStream os = response.getOutputStream();
	    			while((len = bis.read(buffer, 0, MAX_SIZE)) != -1) {
	    				os.write(buffer, 0, len);
	    			}
	    			os.flush();
	    			os.close();
	    			return AjaxResult.success("下载成功");
		    	} catch(Exception e) {
		    		e.printStackTrace();
		    	} finally {
		    		if(bis != null) {
		    			try {
							bis.close();
						} catch (IOException e) {
							e.printStackTrace();
						}
		    		}
		    	}
			} else {
    			AjaxResult.error("文件不存在");
    		}
		}
        return AjaxResult.error("下载失败");
    }
	
}
